
//
//  UserAccount.swift
//  MyBlog
//
//  Created by lvtienan on 15/7/31.
//  Copyright © 2015年 ltn. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {
    
    // 用户是否登录标记
    class var userLogin: Bool {
        return loadAccount() != nil
    }
    
//    access_token	string	用于调用access_token，接口获取授权后的access token。
//    expires_in	string	access_token的生命周期，单位是秒数。
//    remind_in	string	access_token的生命周期（该参数即将废弃，开发者请使用expires_in）。
//    uid	string	当前授权用户的UID。
    var access_token: String?
    // access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var expiresDate: NSDate?
    var uid:String?
    
    // 友好显示名称
    var name: String?
    //用户头像地址(大图)
    var avatar_large: String?
    
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
        // 设置全局的用户信息
        UserAccount.userAccount = self
        
        // expiresDate = NSDate(timeIntervalSinceNow: expires_in)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    
    // CustomStringConvertible
    override var description: String {
        let properies = ["access_token", "expires_in", "uid","expiresDate", "name", "avatar_large"]
        // 模型转字典
       return "\(dictionaryWithValuesForKeys(properies))"
    }
    
    // MARK: - 加载用户信息
    func loaduserInfo(finished: (error: NSError?) -> ()) {
        NetworkTools.sharedNetworkTools.loaduserInfo(uid!) { (result, error) -> () in
            if error != nil {
                finished(error: error)
                return
            }
            
            // 设置用户信息
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            // 保存用户信息
            self.saveAccount()
            
            finished(error: nil)
        }
    }
    
    // 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey:"access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey:"uid")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    // 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    // 保存文件路径
    static private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
    // 保存用户帐号
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    }
    
    // 加载帐号
    // 如果没有登录,返回空
    // 如果 token 过期 ,返回空
    
    // 
    private  static var userAccount: UserAccount?
    
    class func loadAccount() -> UserAccount? {
        
        if userAccount == nil {
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        }
        
        if let date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            userAccount = nil
        }
        return userAccount
    }
}



